package com.pospi.xstore.ui.report;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.caigou.CgddBeen;
import com.pospi.xstore.ui.xs.SaleDetailActivity;
import com.pospi.xstore.ui.xs.SearchXsBillActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

public class KHBillListActivity extends BaseActivity {

    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;
    @Bind(R.id.tv_list_title)
    TextView tv_list_title;




    private List<KhbillBeen> beens = new ArrayList<>();
    private String count;
    private String je;
    private MyAdapter adapter;
    private KhBeen khBeen;
    private String person1;
    private String custid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_khbill_list);
        ButterKnife.bind(this);
        setTitle("单据列表");
        setMenuImage(R.drawable.icon_search_white);
        person1 = getIntent().getStringExtra("person1");
        custid = getIntent().getStringExtra("custid");
        init();
        downStore();
        downSup();
        downCus();
    }
    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        Intent intent = new Intent(this, SearchBillActivity.class);
        startActivity(intent);

    }



    private void init() {
        switch_button.setText("今天","昨天","近三天","近一周","近一月");
        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                switch (position) {
                    case 0:
                        startrq = GetData.getAnyTime(0);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 1:
                        startrq = GetData.getAnyTime(1);
                        endrq = GetData.getAnyTime(1);
                        searchBillfast();
                        break;
                    case 2:
                        startrq = GetData.getAnyTime(3);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 3:
                        startrq = GetData.getAnyTime(7);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 4:
                        startrq = GetData.getAnyTime(30);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                }
            }
        });
        tv_list_title.setText("没有查询到数据");

        ListView bill_list = (ListView) findViewById(R.id.list_bill);
        adapter = new MyAdapter();
        bill_list.setAdapter(adapter);
        bill_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(KHBillListActivity.this, KHDetailActivity.class);
                intent.putExtra("id", beens.get(i).getId());
                intent.putExtra("type", beens.get(i).getType());
                startActivity(intent);
            }
        });
        searchBillfast();

    }
    private String startrq = GetData.getAnyTime(0);
    private String endrq = GetData.getAnyTime(0);
    private String billno;
    private String market;
    private String status;
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch_button.clearSelection();
        beens.clear();
        startrq = intent.getStringExtra("startrq");
        endrq = intent.getStringExtra("endrq");
        billno = intent.getStringExtra("billno");
        market = intent.getStringExtra("market");
        status = intent.getStringExtra("status");
        searchBillfast();

    }

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return beens.size();
        }

        @Override
        public Object getItem(int i) {
            return beens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder ;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(KHBillListActivity.this).inflate(R.layout.kh_detail_item, null);
                holder.statusname = view.findViewById(R.id.statusname);
                holder.billno = view.findViewById(R.id.billno);
                holder.je = view.findViewById(R.id.je);
                holder.billrq = view.findViewById(R.id.billrq);
                holder.marketname = view.findViewById(R.id.marketname);
                holder.supname = view.findViewById(R.id.supname);
                holder.tv_qkje = view.findViewById(R.id.tv_qkje);
                holder.tv_payje = view.findViewById(R.id.tv_payje);
                holder.tv_ye = view.findViewById(R.id.tv_ye);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            KhbillBeen cgddBeen = beens.get(i);
            holder.supname.setText(cgddBeen.getName());
            holder.statusname.setText(cgddBeen.getTypename());
            holder.billrq.setText(cgddBeen.getBillrq());
            holder.billno.setText(cgddBeen.getBillno());
            holder.tv_qkje.setText("欠款："+cgddBeen.getQkje());
            holder.tv_payje.setText("已收："+cgddBeen.getPayje());
            holder.tv_ye.setText("应收："+cgddBeen.getYe());

            return view;
        }
        class Holder{
            TextView statusname;
            TextView billno;
            TextView je;
            TextView billrq;
            TextView marketname;
            TextView supname;
            TextView tv_qkje;
            TextView tv_payje;
            TextView tv_ye;

        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    if (beens.size() == 0) {
                        setbill(false);
                        adapter.notifyDataSetChanged();
                    } else {
                        setbill(true);
                        adapter.notifyDataSetChanged();
                    }

                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };
    private void setbill(boolean o){
        if (o) {

            tv_list_title.setVisibility(View.GONE);

        } else {
            tv_list_title.setVisibility(View.VISIBLE);
            tv_list_title.setText("没有查询到数据");

            beens.clear();
            adapter.notifyDataSetChanged();
        }

    }


    //下载门店
    private void downStore() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.STORE_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载客户
    private void downSup() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getsupplier");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.SUP_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载客员工
    private void downCus() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getperson");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.CUS_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }




    private void searchBillfast() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "report.Mwltj");
        params.put("fun", "find_custwlmx");

//        params.put("page", "");
//        params.put("limit", "");


        JSONObject object = new JSONObject();
        try {
            object.put("startrq", startrq);
            object.put("endrq", endrq);
            object.put("billno", billno);
            object.put("market", market);
            object.put("custid", custid);
            object.put("person1", person1);
            object.put("status", status);
//            object.put("filter", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    List<KhbillBeen> cgddBeens = new Gson().fromJson(result.toString(),
                            new TypeToken<List<KhbillBeen>>() {
                            }.getType());
                    beens.clear();
                    beens.addAll(cgddBeens);
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

}
